package com.cqhz.quwan.ui.main.fragment


import android.app.Dialog
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.StringUtils.isEmpty
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.mine.MineContract
import com.cqhz.quwan.mvp.mine.MinePresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.activity.MallActivity
import com.cqhz.quwan.ui.activity.MyCouponActivity
import com.cqhz.quwan.ui.activity.MyExchangeActivity
import com.cqhz.quwan.ui.activity.RechargeActivity
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.activity.MyPredictionActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.main.order.MyPushOrderActivity
import com.cqhz.quwan.ui.main.order.OrderListActivity
import com.cqhz.quwan.ui.mine.*
import com.cqhz.quwan.ui.widget.dialog.PrizeDialog
import com.cqhz.quwan.ui.widget.dialog.RewardDialog
import com.cqhz.quwan.util.*
import kotlinx.android.synthetic.main.fragment_mine.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject


/**
 * 首页-我的页面
 * Created by Guojing on 2018/9/4.
 */
class MineFragment : AbsFragment(), LoginSubscribe, MineContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var minePresenter: MinePresenter
    private var loginBean: LoginBean? = null
    private var userInfoBean: UserInfoBean? = null
    private var dialog: Dialog? = null
    private var systemConfigBean: SystemConfigBean? = null

    override fun initImmersionBar() {
        mImmersionBar!!.transparentStatusBar().init()
    }

    override fun login(loginBean: LoginBean?) {
        this@MineFragment.loginBean = loginBean
    }

    override fun inject(t: ActivityInject?) {
        t!!.inject(this)
    }

    companion object {
        fun newInstance() = MineFragment()
    }

    override fun layout(): Int {
        return R.layout.fragment_mine
    }

    override fun initView() {
        LoginObserver.register(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
            minePresenter.getUserInfo(loginBean!!.userId!!)
        }
        minePresenter.attachView(this)
        minePresenter.getSystemConfig(KeyContract.MY_QUIZ_SWITCH)
        minePresenter.getSystemConfig(KeyContract.SIGN_IN_SWITCH)
        // 去登录
        action_goto_login.setOnClickListener { startActivity(Intent(activity, LoginActivity::class.java)) }
        // 个人信息
        action_goto_personal_setting.setOnClickListener {
            startActivity(Intent(activity, if (APP.get()!!.loginInfo == null) LoginActivity::class.java else InformationActivity::class.java))
        }
        // 签到
        action_sign.setOnClickListener {
            if (APP.get()!!.loginInfo == null) {
                startActivity(Intent(context, LoginActivity::class.java))
                return@setOnClickListener
            }

            if (systemConfigBean != null && systemConfigBean!!.type == 0 && !StringUtils.isEmpty(systemConfigBean!!.cval)) {
                val intent = Intent(context(), WebViewActivity::class.java)
                intent.putExtra(KeyContract.Title, "任务中心")
                intent.putExtra(KeyContract.Url, systemConfigBean!!.cval)
                intent.putExtra(KeyContract.EnableRefresh, false)
                startActivity(intent)
                return@setOnClickListener
            }

            minePresenter.mineSign(loginBean!!.userId!!)
            minePresenter.getUserInfo(loginBean!!.userId!!)
        }
        // 趣豆跳转
        action_goto_bean.setOnClickListener { gotoActivity(BeanActivity::class.java) }
        // 钻石记录
        action_goto_diamond_record.setOnClickListener { gotoActivity(DiamondRecordActivity::class.java) }
        // 充值
        action_goto_recharge.setOnClickListener { gotoActivity(RechargeActivity::class.java) }
        // 抽钻
        action_goto_diamond.setOnClickListener { gotoExchangeDiamonds() }
        // 我的红包
        action_goto_coupon.setOnClickListener { gotoActivity(MyCouponActivity::class.java) }
        // 我的竞猜
        action_goto_guess.setOnClickListener { gotoActivity(OrderListActivity::class.java) }
        // 我的预测
        action_goto_prediction.setOnClickListener { gotoActivity(MyPredictionActivity::class.java) }
        // 钻石商城
        action_goto_mall.setOnClickListener { gotoActivity(MallActivity::class.java) }
        // 我的领奖
        action_goto_reward.setOnClickListener { gotoActivity(MyExchangeActivity::class.java) }
        // 我的推单
        action_goto_my_push_order.setOnClickListener { gotoActivity(MyPushOrderActivity::class.java) }
        // 我的佣金
        action_goto_my_commission.setOnClickListener { gotoActivity(MyCommissionActivity::class.java) }
        // 消息中心
        action_goto_message.setOnClickListener {
            gotoActivity(MessageActivity::class.java)
        }
        // 官方QQ群
        action_qq_group.setOnClickListener {
            val cm = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            cm.text = userInfoBean!!.officialQQGroup
            Toast.makeText(context, "已复制到剪贴板", Toast.LENGTH_SHORT).show()
        }
        // 帮助中心
        action_goto_help.setOnClickListener {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "帮助中心")
            intent.putExtra(KeyContract.Url, API.H5_Help)
            startActivity(intent)
        }
        // 论坛交流
        action_goto_feedback.setOnClickListener {
            // 论坛功能实现：https://tucao.qq.com/helper/configLogonState
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "论坛交流")
            intent.putExtra(KeyContract.Url, API.LunTan)
            intent.putExtra(KeyContract.EnableRefresh, false)
            startActivity(intent)
        }
        // 设置
        action_goto_setting.setOnClickListener { gotoActivity(SettingsActivity::class.java) }
    }

    /**
     * 去抽钻
     */
    private fun gotoExchangeDiamonds() {
        val intent = Intent(context(), WebViewActivity::class.java)
        intent.putExtra(KeyContract.Title, "趣豆寻宝")
        intent.putExtra(KeyContract.Url, API.findTreasure)
        startActivity(intent)
    }

    /**
     * 跳转到其他页面
     * @author Guojing
     */
    private fun gotoActivity(c: Class<*>) {
        startActivity(Intent(activity, if (APP.get()!!.loginInfo == null) LoginActivity::class.java else c))
    }

    override fun showUserInfo(userInfoBean: UserInfoBean) {
        this.userInfoBean = userInfoBean
        setLoginStyle(true)
        action_goto_info.setLoadImage(context(), userInfoBean.headAddress, R.mipmap.iv_default_head)// 用户头像
        tv_nick_name.text = userInfoBean.nickName
        tv_phone.text = userInfoBean.mobile.displayNumber()
        tv_funny_bean.text = userInfoBean.balance.formatNoZero()// 趣豆
        tv_diamonds.text = userInfoBean.diamonds.formatNoZero()// 钻石
        tv_coupon.text = userInfoBean.couponNum.formatNoZero()// 优惠券
        tv_qq_group.text = userInfoBean.officialQQGroup// 官方QQ群
    }

    override fun showAlreadyMsg(boolean: Boolean) {
        iv_message_new.visibility = if (boolean) View.VISIBLE else View.GONE
    }

    /**
     * 加载广告
     * @param mineAd 广告数据
     */
    override fun loadBanner(list: List<BannerItem>) {
        action_goto_ad?.visibility = if (!isEmpty(list[0].imgUrl)) View.VISIBLE else View.GONE

        if (!TextUtils.isEmpty(list[0].imgUrl)) {
            action_goto_ad.setLoadImage(context!!, list[0].imgUrl, 0)
            action_goto_ad?.setOnClickListener {
                val intent = Intent(context, WebViewActivity::class.java)
                intent.putExtra(KeyContract.Title, "邀请好友")
                intent.putExtra(KeyContract.Url, "${list[0].linkUrl}?user_id=${loginBean?.userId
                        ?: ""}&new=123")
                intent.putExtra(KeyContract.EnableRefresh, false)
                startActivity(intent)
            }
        }
    }

    override fun setSystemConfig(systemConfigBean: SystemConfigBean) {
        when (systemConfigBean.ckey) {
            KeyContract.MY_QUIZ_SWITCH -> {
                v_guess.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
                action_goto_guess.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
                v_prediction.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
                action_goto_prediction.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
                v_push_order.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
                action_goto_my_push_order.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
                v_commission.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
                action_goto_my_commission.visibility = if (systemConfigBean.cval == "1") View.VISIBLE else View.GONE
            }
            KeyContract.SIGN_IN_SWITCH -> {
                this.systemConfigBean = systemConfigBean
            }
        }
    }

    override fun setWindowList(list: List<WindowBean>) {
        // type 类型 1-中奖；2-邀请首单；3-邀请首冲；4-每日首单；5-新用户注册
        for (i in list.size - 1 downTo 0) {
            when (list[i].type) {
                "1" -> {
                    PrizeDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(activity, if (loginBean == null) LoginActivity::class.java else OrderListActivity::class.java)) }
                            .show()
                }
                "6" -> {
                    PrizeDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(activity, if (loginBean == null) LoginActivity::class.java else MyPredictionActivity::class.java)) }
                            .show()
                }
                else -> {
                    RewardDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("确定")
                            .show()
                }
            }
        }
    }

    /**
     **设置登录样式
     * @param isLogin 是否已登录
     */
    private fun setLoginStyle(isLogin: Boolean) {
        if (!isLogin) {
            tv_funny_bean.text = "0"
            tv_diamonds.text = "0"
            tv_coupon.text = "0"
        }
        ll_info.visibility = if (isLogin) View.VISIBLE else View.GONE
        action_goto_login.visibility = if (!isLogin) View.VISIBLE else View.GONE
    }

    override fun showTips(msg: String) {
        showToast(msg)

        dialog = Dialog(context, R.style.ImageDialogStyle)
        dialog!!.setContentView(R.layout.layout_image_dialog)
        val imageView = dialog!!.findViewById(R.id.iv_dialog) as ImageView
        imageView.setLoadImage(context(), null, R.drawable.img_success)
        // 选择true的话点击其他地方可以使dialog消失，为false的话不会消失
        dialog!!.setCanceledOnTouchOutside(true) // Sets whether this dialog is
        val w = dialog!!.window
        val lp = w.attributes
        lp.x = 0
        lp.y = 40
        dialog!!.onWindowAttributesChanged(lp)
        imageView.setOnClickListener {
            minePresenter.getUserInfo(loginBean!!.userId!!)
            dialog!!.dismiss()
        }
        dialog!!.show()
    }

    override fun onResume() {
        super.onResume()
        UmengAnalyticsHelper.onPageStart("我的")// 统计页面
        UmengAnalyticsHelper.onResume(context())
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo

        }
        setLoginStyle(loginBean != null)
        minePresenter.getBannerData()
        if (loginBean != null) {
            minePresenter.getUserInfo(loginBean!!.userId!!)
            minePresenter.hasMsgNew(loginBean!!.userId!!)
            minePresenter.getWindowList(loginBean!!.userId!!)
            UserInfoObserver.push(null)
        } else {
            setLoginStyle(false)
            UserInfoObserver.push(null)
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!isHidden) {
            this.onResume()
        } else {
            this.onPause()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LoginObserver.unregister(this)
        minePresenter.detachView()
    }

    override fun onPause() {
        super.onPause()
        UmengAnalyticsHelper.onPageEnd("我的")// 统计页面
        UmengAnalyticsHelper.onPause(context())
    }
}
